package ar.edu.utn.frba.dds.tp.homes;

import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import uqbar.arena.persistence.PersistentHome;
import ar.edu.utn.frba.dds.tp.code.adapter.LanchitaAdapter;
import ar.edu.utn.frba.dds.tp.code.vuelos.Aerolinea;

@SuppressWarnings("serial")
public class AerolineasHome extends PersistentHome<Aerolinea> implements Serializable{

	private static AerolineasHome instance = new AerolineasHome();
	
	public static AerolineasHome getInstance() {
		return instance;
	}
	
	
	
	
	@Override
	public Class<Aerolinea> getEntityType() {
		return Aerolinea.class;
	}

	@Override
	public Aerolinea createExample() {
		return new LanchitaAdapter();
	}


	public void crearSiCorresponde(Aerolinea aerolinea) {

		Aerolinea example;
		
			Constructor<? extends Aerolinea> cons;
			try {
				cons = aerolinea.getClass().getDeclaredConstructor(aerolinea.getClass().getSuperclass());
			} catch (NoSuchMethodException e) {
				throw new RuntimeException("Falló al encontrar el constructor",e);
			} catch (Exception e) {
				throw new RuntimeException("Algo salió mal...",e); 
			}
			cons.setAccessible(true);
			try {
				example = cons.newInstance(aerolinea);
			} catch (IllegalArgumentException e) {
				throw new RuntimeException("Illegal ARgument", e); 
			} catch (InstantiationException e) {
				throw new RuntimeException("Instantiation Ex", e); 
			} catch (IllegalAccessException e) {
				throw new RuntimeException("Illegal Access", e); 
			} catch (InvocationTargetException e) {
				throw new RuntimeException("Invocation Target Ex", e); 
			}
//			throw new RuntimeException("No pudo instanciarse otra Aerolinea " + aerolinea.getName(), e);
		example.setVuelos(null);
		if (this.searchByExample(example).isEmpty()) {
			this.create(aerolinea);
		}
	}

}
